package cn.ehanghai.iot.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;

import java.io.File;


/**
 * Created by allenwc on 16/2/24.
 */
public class OSSUtil {

    public static final String FOLDER_THIRD_API_JSON = "api_json/";
    public static final String BUCKET_NAME_SOURCE = "sw-source";

    private static String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";

    private static String ACCESS_KEY_ID = "jYMpdj9CYWsw5K7a";

    private static String ACCESS_KEY_SECRET = "ptFV7F8hckHq0qFiske0MEymLdC8ye";

    public static File downToFile(String bucketName, String key, String savePath, String fileName) {
        // TODO Auto-generated method stub
        OSSClient client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        File folder = new File(savePath);
        if (!folder.exists() || !folder.isDirectory()) {
            folder.mkdirs();
        }
        File file = new File(savePath + "/" + fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            client.getObject(new GetObjectRequest(bucketName, key), file);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        // 关闭client
        client.shutdown();
        if (file.exists()) {
            return file;
        }
        return null;
    }
}